package com.flower.background.controller;

import com.flower.entity.User;
import com.flower.service.UserService;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.flower.utils.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * UserController 控制器类
 * @date 2019-03-06 14:09:49
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	/** 查询全部方法 */
	@GetMapping("/findAll")
	public List<User> findAll() {
		return userService.findAll();
	}

	/** 多条件分页查询方法 */
	@GetMapping("/findByPage")
	public PageResult findByPage(User user, Integer page, Integer rows) {

		try{
			//        处理get方式请求参数乱码
			if(user!=null&& StringUtils.isNoneBlank(user.getName())){
				user.setName(new String(user.getName().getBytes("ISO8859-1"),"UTF-8"));
			}
			if(user!=null&& StringUtils.isNoneBlank(user.getNickname())){
				user.setNickname(new String(user.getNickname().getBytes("ISO8859-1"),"UTF-8"));
			}

		}catch (Exception e){
			e.printStackTrace();
		}

		try {
			return userService.findByPage(user, page, rows);
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return null;
	}

	/** 根据主键id查询方法 */
	@GetMapping("/findOne")
	public User findOne(Long id) {
		try {
			return userService.findOne(id);
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return null;
	}

	/** 添加方法 */
	@PostMapping("/save")
	public boolean save(@RequestBody User user) {
		String brithday = user.getBrithday();
		System.out.println("old===="+brithday);
		String[] ts = brithday.split("T");
		if (ts.length>0){
			user.setBrithday(ts[0]);
			System.out.println(ts[0]);
		}

		try {
			userService.save(user);
			return true;
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return false;
	}

	/** 修改方法 */
	@PostMapping("/update")
	public boolean update(@RequestBody User user) {

		String brithday = user.getBrithday();
		System.out.println("old===="+brithday);
		String[] ts = brithday.split("T");
		if (ts.length>0){
			user.setBrithday(ts[0]);
			System.out.println(ts[0]);
		}

		try {
			userService.update(user);
			return true;
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return false;
	}


	/** 删除方法 */
	@GetMapping("/delete")
	public boolean delete(Long[] ids) {
		try {
			userService.deleteAll(ids);
			return true;
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return false;
	}


}
